package com.yuanqi.java.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanqi.java.dto.PurchaseOrderAuditDTO;
import com.yuanqi.java.dto.PurchaseOrderDTO;
import com.yuanqi.java.dto.PurchaseOrderItemDTO;
import com.yuanqi.java.entity.PurchaseOrder;
import com.yuanqi.java.entity.PurchaseOrderAudit;
import com.yuanqi.java.entity.PurchaseOrderItem;
import com.yuanqi.java.entity.Product;
import com.yuanqi.java.mapper.PurchaseOrderMapper;
import com.yuanqi.java.service.IPurchaseOrderAuditService;
import com.yuanqi.java.service.IPurchaseOrderItemService;
import com.yuanqi.java.service.IPurchaseOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 采购订单主表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-08-27
 */
@Service
public class PurchaseOrderServiceImpl extends ServiceImpl<PurchaseOrderMapper, PurchaseOrder> implements IPurchaseOrderService {
    
    @Autowired
    private IPurchaseOrderItemService purchaseOrderItemService;
    
    @Autowired
    private IPurchaseOrderAuditService purchaseOrderAuditService;
    
    @Autowired(required = false)
    private com.baomidou.mybatisplus.extension.service.IService<Product> productService;

    @Override
    public Long createPurchaseOrder(PurchaseOrderDTO purchaseOrderDTO) {
        //创建采购订单主表
        PurchaseOrder purchaseOrder=new PurchaseOrder();
        BeanUtils.copyProperties(purchaseOrderDTO,purchaseOrder);
        //生成订单号
        purchaseOrder.setOrderNo(generateOrderNo());
        purchaseOrder.setCreateTime(LocalDateTime.now());
        purchaseOrder.setStatus(0);
        //计算总金额
        BigDecimal totalAmount=BigDecimal.ZERO;
        if (purchaseOrderDTO.getItems()!=null){
            totalAmount=purchaseOrderDTO.getItems().stream()
                    .map(item->item.getPrice().multiply(new BigDecimal(item.getQuantity())))
                    .reduce(BigDecimal.ZERO,BigDecimal::add);
        }
        purchaseOrder.setTotalAmount(totalAmount);
        //保存主表
        save(purchaseOrder);
        //保存明细表
        if (purchaseOrderDTO.getItems() != null) {
            List<PurchaseOrderItem> items = purchaseOrderDTO.getItems().stream()
                    .map(itemDTO -> {
                        PurchaseOrderItem item = new PurchaseOrderItem();
                        BeanUtils.copyProperties(itemDTO, item);
                        item.setOrderId(purchaseOrder.getId());
                        item.setAmount(item.getPrice().multiply(new BigDecimal(item.getQuantity())));
                        return item;
                    })
                    .collect(Collectors.toList());
            purchaseOrderItemService.saveBatch(items);
        }
        return purchaseOrder.getId();
    }

    @Override
    public boolean deletePurchaseOrder(Long orderId) {
        //检查订单状态，草稿状态能删除
        PurchaseOrder order = getById(orderId);
        if (order==null){
            throw new RuntimeException("订单不存在");
        }
        if(order.getStatus()!=0){
            throw new RuntimeException("草稿状态才能删除");
        }
        //删除明细
        QueryWrapper<PurchaseOrderItem> itemWrapper = new QueryWrapper<>();
        itemWrapper.eq("order_id",orderId);
        purchaseOrderItemService.remove(itemWrapper);
        return removeById(orderId);
    }

    @Override
    public boolean submitForAudit(Long orderId) {
        PurchaseOrder order = getById(orderId);
        if (order==null){
            throw new RuntimeException("订单不存在");
        }
        if (order.getStatus()!=0){
            throw new RuntimeException("只有草稿状态的订单才能提交");
        }
        //更新状态为审核
        order.setStatus(1);
        return updateById(order);
    }

    @Override
    public boolean auditPurchaseOrder(PurchaseOrderAuditDTO auditDTO) {
        PurchaseOrder order = getById(auditDTO.getOrderId());
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (order.getStatus() != 1) {
            throw new RuntimeException("只有待审核状态的订单才能审核");
        }

        // 创建审核记录
        PurchaseOrderAudit audit = new PurchaseOrderAudit();
        BeanUtils.copyProperties(auditDTO, audit);
        if (audit.getAuditorId() == null) {
            // 若未从网关传递用户信息，避免数据库非空约束报错
            audit.setAuditorId(0L);
        }
        audit.setAuditTime(LocalDateTime.now());
        purchaseOrderAuditService.save(audit);

        // 更新订单状态
        if (auditDTO.getAuditResult() == 1) {
            // 审核通过
            order.setStatus(2);
        } else {
            // 审核驳回
            order.setStatus(0);
        }

        return updateById(order);
    }

    @Override
    public PurchaseOrderDTO getPurchaseOrderDetail(Long orderId) {
        PurchaseOrder order = getById(orderId);
        if (order == null) {
            return null;
        }

        PurchaseOrderDTO dto = new PurchaseOrderDTO();
        BeanUtils.copyProperties(order, dto);

        // 查询明细
        QueryWrapper<PurchaseOrderItem> itemWrapper = new QueryWrapper<>();
        itemWrapper.eq("order_id", orderId);
        List<PurchaseOrderItem> items = purchaseOrderItemService.list(itemWrapper);

        // 可选：填充商品名和编码，便于前端展示
        Map<Long, Product> computedMap;
        if (productService != null && !items.isEmpty()) {
            List<Long> productIds = items.stream().map(PurchaseOrderItem::getProductId).distinct().collect(Collectors.toList());
            List<Product> products = productService.list(new QueryWrapper<Product>().in("id", productIds));
            computedMap = products.stream().collect(Collectors.toMap(Product::getId, Function.identity()));
        } else {
            computedMap = java.util.Collections.emptyMap();
        }
        final Map<Long, Product> productMap = computedMap;

        List<PurchaseOrderItemDTO> itemDTOs = items.stream()
                .map(item -> {
                    PurchaseOrderItemDTO itemDTO = new PurchaseOrderItemDTO();
                    BeanUtils.copyProperties(item, itemDTO);
                    Product p = productMap.get(item.getProductId());
                    if (p != null) {
                        itemDTO.setProductName(p.getProductName());
                        itemDTO.setProductCode(p.getSpuCode());
                    }
                    return itemDTO;
                })
                .collect(Collectors.toList());

        dto.setItems(itemDTOs);
        return dto;
    }
    /**
     * 生成订单编号
     */
    private String generateOrderNo() {
        return "PO_" + LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
    }
}
